package com.wdz.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtil {

    /**
     * 获取资源包下的文件路径
     *
     * @param path 文件名
     * @return
     * @throws IOException
     */
    public String getResourcePath(String path) throws IOException {
        Resource r = new ClassPathResource(path);
        File f = r.getFile();
        r.getInputStream();

        f = r.getFile();
        System.out.println("获取到resource下的文件" + path + "路径为" + f.getPath());
        return f.getPath();
    }

    /**
     * 上传文件
     *
     * @param file     文件
     * @param basePath 上传路径
     * @param fileName 文件名
     * @return true:成功 false:失败
     * @throws IOException 抛出异常
     */
    public static boolean uploadFile(MultipartFile file, String basePath, String fileName) throws IOException {

        // 判断文件是否为空，空则返回失败页面
        if (file.isEmpty()) {
            return false;
        }
        // 获取文件存储路径（绝对路径）
        //String path = req.getServletContext().getRealPath("/WEB-INF/file");
        // 获取原文件名
        //String fileName = file.getOriginalFilename();
        //根据uuid生成文件名
        //String fileName = UUID.randomUUID().toString().replaceAll("-", "")+file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        // 创建文件实例
        File uploadFile = new File(basePath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        // String originalFilename = file.getOriginalFilename();
        //if (originalFilename != null && !originalFilename.equals("")) {
        try {
            // 对文件名做加UUID值处理
            //originalFilename = UUID.randomUUID() + "_" + originalFilename;
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
       /* } else {
            return false;
        }*/
        return true;
    }

    /**
     * 将字符串转换成指定类型的文本并生成
     *
     * @param basePath 上传路径
     * @param type     文件类型 1:html 2:txt
     * @param value    文件内容
     * @param fileName 文件名称
     * @return true:成功 false:失败
     */
    public static boolean strToMakeFile(String basePath, int type, String value, String fileName) {
        //String str = "";

        //StringBuffer buffer = new StringBuffer();


            /*try {
                    String tempStr = "";
                    InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
                    BufferedReader br = new BufferedReader(isr);
                    while ((tempStr = br.readLine()) != null){
                         str = str + tempStr +"\n";
                    }
            } catch (IOException e) {
                    e.printStackTrace();
                    return false;
            }*/

        /*try {
            URL url = new URL(filePath);
            HttpURLConnection httpUrl = (HttpURLConnection)url.openConnection();
            InputStream is = httpUrl.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line+"\n");
            }
            is.close();
            br.close();
        } catch (Exception e) {

        }*/
        // 创建文件实例
        File uploadFile = new File(basePath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        try {
            //str = buffer.toString().replaceAll("###imageUrl###","http://img.zcool.cn/community/0142135541fe180000019ae9b8cf86.jpg@1280w_1l_2o_100sh.png");
            //必须设置编码格式不然会出现乱码
            StringBuffer filePath = new StringBuffer(basePath);
            StringBuffer str = new StringBuffer();
            filePath.append("/");
            filePath.append(fileName);
            if (type == 1) {//1为生成html文件
                filePath.append(".html");
            } else if (type == 2) {//2为生成txt文件
                filePath.append(".txt");
            }
            str.append(value);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath.toString()), "UTF-8"));
            bufferedWriter.write(str.toString());
            bufferedWriter.newLine();//换行
            bufferedWriter.flush();
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 生成txt文件并返回
     */
    public static File strToMakeTxtReturnFile(String basePath, String value, String fileName) throws IOException {
        // 创建文件实例
        File uploadFile = new File(basePath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }

        //str = buffer.toString().replaceAll("###imageUrl###","http://img.zcool.cn/community/0142135541fe180000019ae9b8cf86.jpg@1280w_1l_2o_100sh.png");
        //必须设置编码格式不然会出现乱码
        StringBuilder filePath = new StringBuilder(basePath);
        filePath.append("/");
        filePath.append(fileName);
        filePath.append(".txt");
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath.toString()), "UTF-8"));
        bufferedWriter.write(value);
        bufferedWriter.newLine();//换行
        bufferedWriter.flush();
        bufferedWriter.close();

        return new File(filePath.toString());
    }

    /**
     * 生成HTML文件并上传
     *
     * @param basePath 上传路径
     * @param value    文件内容
     * @param fileName 文件名称
     * @return
     */
    public static boolean strToMakeHtml(String basePath, String value, String fileName) {
        return strToMakeFile(basePath, 1, value, fileName);
    }

    /**
     * 生成TXT文件并上传
     *
     * @param basePath 上传路径
     * @param value    文件内容
     * @param fileName 文件名称
     * @return
     */
    public static boolean strToMakeTxt(String basePath, String value, String fileName) {
        return strToMakeFile(basePath, 2, value, fileName);
    }

    /**
     * 生成文件名
     *
     * @return
     */
    public static String makeFileName() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 根据文件生成文件名
     *
     * @param file 文件
     * @return
     */
    public static String makeFileName(MultipartFile file) {
        return UUID.randomUUID().toString().replaceAll("-", "") + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
    }

    public static String FileToStr(int type, String filePath) throws IOException {
        File file = new File(filePath);
        byte[] bytes = FileCopyUtils.copyToByteArray(file);
        String str = new String(bytes);
        if (type == 1) {
            return str.substring(105, str.length() - 17);
        }
        return str;
    }

    public static void main(String[] args) throws IOException {
        //System.out.println(FileToStr(1,"G:/dongzheBK/fileTest/bk/b627e1f0de354fd0b0cadfa4aeeb66b6.html"));
        String patt = "\\bhttp://localhost:8081/\\b";
        String url = "http://localhost:8081/bk/b627e1f0de354fd0b0cadfa4aeeb66b6.html";
        Pattern r = Pattern.compile(patt);
        Matcher m = r.matcher(url);
        System.out.println(m.replaceAll("G:/dongzheBK/fileTest/"));
    }
}
